<?php
/**
 * Basic class to decode minimal bbcode
 * (unsafe, far from full proof... use with care)
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 */
class ACC_Cache {

    public    $NOTIMEOUT = true;
    protected $cache_dir = '';
    protected $cache_timeout = 21600;//3600*6;

    /**
     *
     */
    public function __construct($cache_dir,$timeout=21600) {
        //TODO: check that provided dir is valid and writable
        $this->cache_dir = $cache_dir;
        if(is_int($timeout)) $this->cache_timeout = $timeout;
    }

    /**
     *
     */
    public function getFile($name,$forced=false){
        if($this->_cacheAvail($name,$forced)) {
            return $this->_readFile($name);
        }
        return false;
    }

    /**
     *
     */
    public function _readFile($name){
        //msg('ACC_Cache::_readFile:'.$this->cache_dir.$name,0);
        return io_readFile($this->cache_dir.$name, false);
        //return '' on error;
    }
    /**
     *
     */
    public function saveFile($name,$contentStr){
        //msg('ACC_Cache::saveFile:'.$this->cache_dir.$name,0);
        return io_saveFile($this->cache_dir.$name,$contentStr);
    }

    /**
     *
     */
    public function setTimeout($timeout){
        $this->cache_timeout = $timeout;
    }

    /**
     *
     */
    protected function _cacheAvail($name,$forced=false) {
        $filename = $this->cache_dir.$name;
        //msg('_cachAvail:'.$filename,0);
        if(@file_exists($filename)){
            if($forced) return true;
            $mtime = @filemtime($filename);
            $now = time();
            $dtime = $now - $mtime;
            //msg('_cachAvail,m:'.date('c',$mtime),0);
            //msg('_cachAvail,n:'.date('c',$now),0);
            //msg('_cachAvail:'.$mtime.":".$now.":".date ('U').":".$dtime.":".$this->cache_timeout,0);
            if($dtime < $this->cache_timeout) return true;
        }
        return false; //TODO: return true if avail and not timeout
    }
}

